import React, { useState } from 'react';
import { Input, message, Spin } from 'antd';
import InfiniteScroll from 'react-infinite-scroller';
import { connect } from 'umi';

import { TRAlert, TRDefault } from '#/components/index.js';
import { DownloadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import { ImportModal, AddQuestion, FileItem, ApplyModal } from './components';
import type { IProps, IQueryFQAParamsType, IPublishFQADataType } from '../type';
import { IOperationType, ISystemHelpCenterPermissions } from '../type';
import {
  postQueryFQA,
  postPublishFQA,
  postUpdateFQA,
  postRemoveFQA,
  batchPublishFQA,
} from '../service';
import { havePermissions } from '../tool';
import styles from './index.less';

const FrequentlyAskedQuestion = (props?: IProps) => {
  const { buttonPermissions = '' } = props || {};
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [hasMore, setHasMore] = useState<boolean>(true);
  const [keywords, setKeywords] = useState<string>('');
  const [total, setTotal] = useState<number>(0);
  const [data, setData] = useState<any[]>([]);

  // 初始化
  const getQueryFQAData = async (params: IQueryFQAParamsType) => {
    setLoading(true);
    setError(false);
    const res = await postQueryFQA(params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setData([...(res?.data?.records || [])]);
      setTotal(res?.data?.total ?? 0);
      setHasMore(res?.data?.total > 50 ? true : false);
    } else {
      setData([]);
      message.error(res?.message || '系统异常');
      setError(true);
    }
    setLoading(false);
  };

  const onSearch = (e: any) => {
    const _params = {
      current: 1,
      keywords: e,
      size: 50,
    };
    setKeywords(e);
    getQueryFQAData(_params);
  };

  const loadMore = async (page: number) => {
    if (!hasMore) return;
    setIsLoading(true);
    setHasMore(total > 50 * (page + 1) ? true : false);
    const _params = {
      current: page + 1,
      keywords,
      size: 50,
    };
    const res = await postQueryFQA(_params);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setTotal(res?.data?.total ?? 0);
      setData([...data, ...(res?.data?.records || [])]);
    } else {
      setData([...data]);
      message.info(res?.message || '系统异常');
    }
    setIsLoading(false);
  };

  // 导入
  const handleDownloadFiles = async () => {
    const resoult = havePermissions(
      ISystemHelpCenterPermissions.SystemHelpCenterImportFQAButton,
      buttonPermissions,
    );
    if (resoult) {
      const result: any = await ImportModal.show({
        onOk: async (params: any) => {
          const res: any = await batchPublishFQA(params);
          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.success('保存成功');
          } else {
            message.error(res?.message || '保存失败');
          }
          return res;
        },
      });
      if (result && result.index === 1 && result.statusCode === HttpCode.SUCCESS) {
        onSearch(keywords);
      }
    }
  };

  const onSave = async (operateType: IOperationType, record?: IPublishFQADataType) => {
    const result: any = await ApplyModal.show({
      total,
      record,
      operateType,
      onOk: async (params: IPublishFQADataType) => {
        if (operateType === IOperationType.ADD) {
          const res: any = await postPublishFQA(params);
          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.success('新增成功');
          } else {
            message.error(res?.message || '新增失败');
          }
          return res;
        } else {
          const res: any = await postUpdateFQA(params);
          if (res && res.statusCode === HttpCode.SUCCESS) {
            message.success('保存成功');
          } else {
            message.error(res?.message || '保存失败');
          }
          return res;
        }
      },
    });
    if (result && result.index === 1 && result.statusCode === HttpCode.SUCCESS) {
      onSearch(keywords);
    }
  };

  // 编辑
  const onEdit = (val?: IPublishFQADataType) => {
    const resoult = havePermissions(
      ISystemHelpCenterPermissions.SystemHelpCenterEditFQAButton,
      buttonPermissions,
    );
    if (resoult) {
      onSave(IOperationType.EDIT, val);
    }
  };

  // 删除
  const onDetele = async (val?: IPublishFQADataType) => {
    const resoult = havePermissions(
      ISystemHelpCenterPermissions.SystemHelpCenterRemoveFQAButton,
      buttonPermissions,
    );
    if (resoult) {
      const obj = await TRAlert.eamDelete('是否确认删除？');
      if (obj?.index === 1) {
        const res: any = await postRemoveFQA({ id: val?.id });
        if (res && res.statusCode === HttpCode.SUCCESS) {
          message.success('删除成功');
          onSearch(keywords);
        } else {
          message.error(res?.message || '删除失败');
        }
      }
    }
  };

  // 新增
  const onAdd = () => {
    const resoult = havePermissions(
      ISystemHelpCenterPermissions.SystemHelpCenterSaveFQAButton,
      buttonPermissions,
    );
    if (resoult) {
      onSave(IOperationType?.ADD);
    }
  };

  React.useEffect(() => {
    const _params = {
      current: 1,
      keywords: '',
      size: 50,
    };
    getQueryFQAData(_params);
  }, []);

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.header}>
          <div className={styles.search}>
            <Input.Search
              placeholder="搜索"
              onSearch={onSearch}
              style={{ minWidth: 389 }}
              allowClear
            />
          </div>
          <div className={styles.button} onClick={handleDownloadFiles}>
            <DownloadOutlined className={styles.buttonLogo} />
            导入
          </div>
        </div>
        <div className={styles.center}>
          {loading ? (
            <Spin />
          ) : error ? (
            <TRDefault type={'error'} message={'系统异常'} />
          ) : (
            <Spin spinning={isLoading} className={styles.spinloading}>
              <div className={styles.list}>
                <InfiniteScroll
                  initialLoad={false}
                  pageStart={0}
                  loadMore={loadMore}
                  hasMore={!loading && hasMore}
                  useWindow={false}
                  className={styles.infiniteScroll}
                >
                  {!keywords && (
                    <div className={styles.item}>
                      {' '}
                      <AddQuestion onAdd={onAdd} />
                    </div>
                  )}
                  {data.map((item: any, index: number) => {
                    return (
                      <div className={styles.item}>
                        <FileItem
                          data={item}
                          onEdit={onEdit}
                          onDetele={onDetele}
                          order={index + 1}
                        />
                      </div>
                    );
                  })}
                </InfiniteScroll>
              </div>
            </Spin>
          )}
        </div>
      </div>
    </div>
  );
};

export default connect(({ systemHelpCenter, global }: { systemHelpCenter: any; global: any }) => ({
  global,
  menuCode: global?.configure?.menuCode,
  systemHelpCenter,
  buttonPermissions: global?.configure?.buttonPermissions,
}))(FrequentlyAskedQuestion);
